// http://mockjs.com/

import Mock from 'mockjs'

import user from './modules/user'
import auth from './modules/auth'

/**
 * @param {...any} argument 打印文本
 */
function log(...argument: string[]) {
  console.log('mockjs', ...argument)
}

const modules: any[] = [
  user,
  auth
]

/**
 * 初始化mock数据
 * @param apiurl 接口url
 */
const initMock = (apiurl: string) => {
  log('已启用mockjs对数据进行虚拟请求')
  log('baseApiUrl', apiurl)
  for (const module of modules) {
    for (const method in module) {
      // 不处理path属性
      if (method === 'path') {
        continue
      }
      for (const action in module[method]) {
        // const url = `${apiurl}${module.path}${action}`
        Mock.mock(
          new RegExp(`${apiurl}${module.path}${action}`),
          method,
          (options: any) => {
            if (
              options.type === 'GET' &&
              options.url.includes('?') &&
              !options.query
            ) {
              options.query = Object.fromEntries(
                new URL(options.url).searchParams.entries()
              )
            }
            const res = module[method][action](options)
            log(`请求： ${options.url}`, res)
            return res
          }
        )
      }
    }
  }
}

export default initMock
